package cn.edu.wfu.libautobook.controller;

import cn.edu.wfu.libautobook.bean.Quartz;
import cn.edu.wfu.libautobook.bean.Result;
import cn.edu.wfu.libautobook.bean.Schedule;
import cn.edu.wfu.libautobook.bean.User;
import cn.edu.wfu.libautobook.mapper.QuartzMapper;
import cn.edu.wfu.libautobook.mapper.UserMapper;
import cn.edu.wfu.libautobook.service.QuartzService;
import cn.edu.wfu.libautobook.service.ScheduleService;
import cn.edu.wfu.libautobook.service.UserService;
import cn.edu.wfu.libautobook.utils.QuartzUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/schedule")
public class ScheduleController {
    @Autowired
    private Scheduler scheduler;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private QuartzService quartzService;
    @Autowired
    private UserService userService;
    private final ScheduleService scheduleService;

    @Autowired
    ScheduleController(ScheduleService scheduleService) {
        this.scheduleService = scheduleService;
    }

    @GetMapping("/get/{sid}")
    public Result get(@PathVariable("sid") Integer sid) {
        if (sid == null) {
            return  null;
        }
        return Result.success(scheduleService.getScheduleBySid(sid));
    }

    @GetMapping("/get/user/{uid}")
    public Result getUserSchedule(@PathVariable("uid") Integer uid) {
        if (uid == null) {
            return null;
        }
        return Result.success(scheduleService.getScheduleListByUid(uid));
    }

    @GetMapping("/get/user")
    public Result getUserSchedule() {
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        if (username == null) {
            return  Result.fail("未认证用户");
        }
        User user = userService.getUserByUsername(username);
        return Result.success(scheduleService.getScheduleListByUid(user.getUid()));
    }

    @PostMapping("/add")
    public Result addSchedule(Schedule schedule) throws ParseException {
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        if (username == null) {
            return Result.fail("未认证用户信息");
        }
        User user = userMapper.queryUserByUsername(username);
        // Create Schedule
        schedule.setCreateTime(new Date());
        schedule.setUid(user.getUid());
        // CreateQuartzSchedule
        Quartz quartz = new Quartz();
        // 设定Quartz
        quartz.setStatus(0);
        quartz.setJobClass("cn.edu.wfu.libautobook.quartz.BookSeat");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(schedule.getTime());
        // 格式化时间表达式
        quartz.setCronExpression(String.format("%d %d %d %d %d ? %d-%d",
                calendar.get(Calendar.SECOND),
                calendar.get(Calendar.MINUTE),
                calendar.get(Calendar.HOUR_OF_DAY),
                calendar.get(Calendar.DATE),
                calendar.get(Calendar.MONTH)+1,
                calendar.get(Calendar.YEAR)-1,
                calendar.get(Calendar.YEAR)));
        quartz.setJobName(user.getUid() + "-" + UUID.randomUUID());
        quartzService.saveSchedule(quartz);
        schedule.setJid(quartz.getJid());
        scheduleService.insertSchedule(schedule);
        QuartzUtils.createScheduleJob(scheduler, quartz, schedule.getSid());
        return Result.success(quartz);
    }

    @DeleteMapping("/cancel/{sid}")
    public Result cancel(@PathVariable("sid") Integer sid) {
        // 获取并清理预约信息
        Schedule schedule = scheduleService.getScheduleBySid(sid);
        Quartz quartz = schedule.getQuartz();
        schedule.setQuartz(null);
        schedule.setUser(null);
        schedule.setEnabled(0);
        schedule.setStates(1);
        scheduleService.updateSchedule(schedule);
        // 删除定时事务
        QuartzUtils.deleteScheduleJob(scheduler, quartz.getJobName());
        // 设置事务状态-
        quartz.setStatus(1);
        quartzService.update(quartz);
        return Result.success("操作完成");
    }
}
